Vue.component("conveyer-ani", {
  props: {
    redpoint: {
      type: Array,
      default: () => [],// 格式例子：[{percent: 1, text: '1'}, {percent: 20, text: '2'}]
    },
    percent: {
      type: Number,
      default: 100
    },
    pause: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      pointList: [],
      startX: 10,
      startY: 20,
      duration: 1,
      svgEle: null,
      motionEle: null,
      totalLen: 0,
      lastPercent: 0,
      curPercent: 0,
      pathSvg: `
                <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1000" height="600">
                  <style>
                    #svgPath {
                      fill: url(#pathPattern);
                    }
                
                    #uPathPatternRect {
                      fill: var(--pathColor, #969696);
                    }
                
                    #uPathPatternRect2 {
                      fill: var(--pathColor2, #888888);
                    }
                  </style>
                  <defs>
                    <path id="svgPath" d="
                      M 0 0
                      L 700 0
                      A 300 300, 0, 0, 1, 700 600
                      L 0 600
                      L 0 500
                      L 700 500
                      A 200 200, 0, 0, 0, 700 100
                      L 0 100
                      L 0 0
                      " />
                    <pattern id="pathPattern" width="0.12" height="0.1">
                      <rect id="uPathPatternRect" width="110" height="100" />
                      <rect id="uPathPatternRect2" width="10" height="100" x="110" />
                    </pattern>
                  </defs>
                  <use id="uPathUse" href="#svgPath" />
                </svg>
              `
    }
  },
  watch: {
    redpoint: {
      handler(newValue, oldValue) {
        this.drawRedPoint();
      },
      deep: true
    },
    percent: {
      handler(newValue, oldValue) {
        this.lastPercent = oldValue;
        this.curPercent = newValue;
      }
    },
    pause: {
      handler(newValue, oldValue) {
        const timer = setTimeout(() => {
          clearTimeout(timer);
          // newValue && this.aniPause();
          // !newValue && this.aniStart();
        }, 200)
      },
      immediate: true
    }
  },
  computed: {
    // 计算路径点位
    pathStr() {
      let pathStr = '';
      let nextPercent = this.curPercent - 1;
      if (nextPercent <= 0) {
        nextPercent = 0;
      }
      let lastItem = [];
      const _pointList = this.pointList;
      _pointList
        .slice(nextPercent, nextPercent + 1)
        .map((item, index) => {
          if (index === 0) {
            pathStr += `M ${item[0]} ${item[1]}`;
          } else {
            pathStr += ` L ${item[0]} ${item[1]}`;
          }
          lastItem = item;
        })
      return pathStr;
    }
  },
  template: `
    <div class="box">
      <div class="shape shape-1"></div>
      <div class="shape shape-2"></div>
      <div class="shape">
        <div class="conveyer">
        <div class="conveyer-content">
          <div class="conveyer-stone" />
        </div>
        </div>
      </div>
      <svg id="path-svg" class="path" xmlns="http://www.w3.org/2000/svg" version="1.1">
        <defs>
          <path id="conveyerPath" :d="pathStr" stroke="transparent" stroke-width="3" fill="transparent" />
          <g id="myMachine">
            <circle cx="25" cy="0" r="20" fill="#fff"/>
            <rect x="0" y="5" width="50" height="50" fill="#030303"/>
          </g>
          <path id="svgPath2" d="
          M 0 30
          L 700 30
          A 230 250, 0, 0, 1, 700 530
          L 0 530"
          stroke="red" 
          fill="transparent"
          />
        </defs>
        <g id="red-point-box">
        </g>
        <use href="#myMachine">
          <animateMotion id="path-svg-motion" :dur="duration +'s'" repeatCount="indefinite">
            <mpath href="#conveyerPath" endElementAt="0.5"  />
          </animateMotion>
        </use>
      </svg>
    </div>
  `,
  mounted() {
    this.svgEle = document.querySelector('#path-svg');
    this.motionEle = document.querySelector('#path-svg-motion');
    this.redPointBox = document.querySelector('#red-point-box');
    this.svgPath2 = document.querySelector('#svgPath2');
    window.motionEle = this.motionEle;
    window.svgPath2 = document.querySelector('#svgPath2');
    this.initPath();
    this.drawRedPoint();
    this.drawPath();
  },
  methods: {
    // 初始化路径
    initPath() {
      const pointList = [];
      const myPath = this.svgPath2;
      const totalLen = myPath.getTotalLength();
      this.totalLen = totalLen;
      const loopTimes = 100;
      const loopPiece = totalLen / 100;
      new Array(loopTimes)
        .fill(0)
        .map((_, index) => {
          const { x, y } = this.getPoint(this.startX + loopPiece * index);
          pointList.push([x, y])
        })
      this.pointList = pointList;
    },
    getPoint(len) {
      return this.svgPath2.getPointAtLength(len);
    },
    // 绘制红点
    drawRedPoint() {
      this.redPointBox.innerHTML = '';
      this.redpoint.map((item, index) => {
        const _pointIndex = item.percent - 1;
        const r = 20;
        const x = this.pointList[_pointIndex][0] + r / 2;
        const y = this.pointList[_pointIndex][1] + r / 2;
        const gEle = document.createElementNS('http://www.w3.org/2000/svg', 'g');
        gEle.innerHTML = `
          <circle cx="${x}" cy="${y + r}" r="${r}" fill="red" />
          <text x="${x - r}" y="${y - r / 3}" fill="red" font-size="20">${item.text}</text>
        `
        this.redPointBox.appendChild(gEle);
      })
    },
    // 绘制轨道
    drawPath() {
      document.querySelector('.shape-1').innerHTML = this.pathSvg
        .replace(/pathPattern/g, 'f-pathPattern')
        .replace(/uPathPatternRect/g, 'f-uPathPatternRect')
        .replace(/svgPath/g, 'f-svgPath');

      document.querySelector('.shape-2').innerHTML = this.pathSvg
        .replace(/pathPattern/g, 's-pathPattern')
        .replace(/uPathPatternRect/g, 's-uPathPatternRect')
        .replace(/svgPath/g, 's-svgPath');
    },
    aniStart() {
      // this.moveToProgress(this.percent);
      this.motionEle.beginElement();
    },
    aniPause() {
      this.motionEle.endElement();
      this.moveToProgress(this.percent);
    },
    moveToProgress(progress) {
      // const currentTime = progress / 100 * this.duration;
      // this.motionEle.beginElementAt(currentTime);
    }
  }
});